import React, { Suspense, useEffect } from "react";
import { Route, Routes, BrowserRouter } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";

import { CSpinner, useColorModes } from "@coreui/react";
import "./scss/style.scss";

import WhiteBoardControl from "./components/whiteboard/WhiteBoardControl";

const DefaultLayout = React.lazy(() => import("./layout/DefaultLayout"));
const Login = React.lazy(() => import("./views/pages/login/Login"));
const Register = React.lazy(() => import("./views/pages/register/Register"));

const App = () => {
  const { isColorModeSet, setColorMode } = useColorModes(
    "coreui-free-react-admin-template-theme"
  );
  const whiteBoardMode = useSelector((state) => state.whiteBoardMode);

  useEffect(() => {
    const urlParams = new URLSearchParams(window.location.href.split("?")[1]);
    const theme =
      urlParams.get("theme") &&
      urlParams.get("theme").match(/^[A-Za-z0-9\s]+/)[0];
    if (theme) {
      setColorMode(theme);
    }

    if (isColorModeSet()) {
      return;
    }
  }, []);

  return whiteBoardMode === false ? (
    <BrowserRouter>
      <Suspense
        fallback={
          <div className="pt-3 text-center">
            <CSpinner color="primary" variant="grow" />
          </div>
        }
      >
        <Routes>
          <Route exact path="/login" name="Login Page" element={<Login />} />
          <Route
            exact
            path="/register"
            name="Register Page"
            element={<Register />}
          />
          <Route exact path="*" name="default" element={<DefaultLayout />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  ) : (
    <WhiteBoardControl />
  );
};

export default App;
